<template>
  <!--display-军容风纪-->
  <div class="discipline-status">
    <div class="module-title">
      军容风纪
      <div
        class="tooltip-container"
        @mouseenter="showTooltip"
        @mouseleave="hideTooltip">
        <button class="info-btn">
          <i class="el-icon-reading"></i>
        </button>
        <!-- 悬停提示框 -->
        <div
          v-show="tooltipVisible"
          class="tooltip-box"
          :style="tooltipStyle">
          {{ disciplineInfoText }}
        </div>
      </div>
    </div>
    <div class="chart-container" ref="barChart"></div>
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DisciplineStatus',
  data() {
    return {
      barChart: null,
      loading: false,
      latestDate: '',
      problemTypes: [],
      problemCounts: [],
      rawData: [],
      // 提示框相关
      tooltipVisible: false,
      disciplineInfoText: '',
      tooltipStyle: {
        position: 'absolute',
        top: '-360px',
        left: '50px',
        zIndex: 1000,
        width: '450px',
        height: '350px'
      }
    };
  },
  mounted() {
    // 延迟加载数据，确保 DOM 已经渲染
    setTimeout(() => {
      this.loadDisciplineInfoText();
      this.loadData();
      window.addEventListener('resize', this.resizeChart);
    }, 500);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.barChart) {
      this.barChart.dispose();
    }
  },
  methods: {
    // 加载军容风纪说明文本
    async loadDisciplineInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"7、"后面的文本，直到下一个序号或文件结束
          const regex = /7、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.disciplineInfoText = match[1].trim();
            console.log('军容风纪说明文本:', this.disciplineInfoText);
          } else {
            console.error('未找到军容风纪说明文本');
            this.disciplineInfoText = '第五十七条 军容风纪是军人的仪表和风貌，是军队作风纪律和战斗力的表现。军人应当配套穿着军服，佩戴军衔、勋表等标志服饰，做到着装整洁庄重、军容严整、规范统一。';
          }
        } else {
          console.error('加载军容风纪说明文本失败');
          this.disciplineInfoText = '第五十七条 军容风纪是军人的仪表和风貌，是军队作风纪律和战斗力的表现。军人应当配套穿着军服，佩戴军衔、勋表等标志服饰，做到着装整洁庄重、军容严整、规范统一。';
        }
      } catch (error) {
        console.error('加载军容风纪说明文本出错:', error);
        this.disciplineInfoText = '第五十七条 军容风纪是军人的仪表和风貌，是军队作风纪律和战斗力的表现。军人应当配套穿着军服，佩戴军衔、勋表等标志服饰，做到着装整洁庄重、军容严整、规范统一。';
      }
    },

    async loadData() {
      this.loading = true;
      try {
        const response = await this.$displayapi.getJRFJ();
        if (!response || !response.data) {
          throw new Error('API返回数据格式错误');
        }

        // 处理数据
        const data = response.data;
        this.problemTypes = data.map(item => item.reason);
        this.problemCounts = data.map(item => parseInt(item.countStudent) || 0);


        // 初始化图表
        this.$nextTick(() => {
          this.initChart();
        });
      } catch (error) {
        console.error('加载风纪数据失败:', error);
        this.$message.error('加载风纪数据失败');
      } finally {
        this.loading = false;
      }
    },

    processData(csvData) {
      console.log('开始处理风纪数据');
      // 分行处理CSV数据
      const rows = csvData.split('\n').filter(row => row.trim() !== '');
      if (rows.length <= 1) {
        console.error('数据行数不足');
        return;
      }

      console.log('数据行数:', rows.length);

      // 解析CSV数据
      this.rawData = [];
      // 第一行是列名，但我们直接使用固定的列索引
      for (let i = 1; i < rows.length; i++) {
        const values = rows[i].split(',');
        if (values.length < 4) continue; // 跳过不完整的行

        // 跳过空行或没有有效数据的行
        if (!values[0] || !values[2] || !values[3]) continue;

        const record = {
          name: values[0].trim(),
          class: values[1] ? values[1].trim() : '',
          problem: values[2].trim(),
          date: values[3].trim()
        };

        this.rawData.push(record);
      }

      console.log('解析后的数据条数:', this.rawData.length);

      // 获取最新日期
      const dates = [...new Set(this.rawData.map(item => item.date))];
      console.log('所有日期:', dates);

      // 如果没有日期数据，使用静态日期
      if (dates.length === 0) {
        this.latestDate = '4月6日';
      } else {
        this.latestDate = dates.sort().pop() || '';
      }

      // 筛选最新日期的数据
      const latestRecords = this.rawData.filter(item => item.date === this.latestDate);
      console.log('最新日期:', this.latestDate);
      console.log('最新日期的数据条数:', latestRecords.length);

      // 统计问题类型及数量
      const problemMap = {};
      latestRecords.forEach(record => {
        if (!problemMap[record.problem]) {
          problemMap[record.problem] = 0;
        }
        problemMap[record.problem]++;
      });

      // 转换为数组格式
      this.problemTypes = Object.keys(problemMap);
      this.problemCounts = this.problemTypes.map(type => problemMap[type]);

      console.log('问题类型:', this.problemTypes);
      console.log('问题数量:', this.problemCounts);

      // 如果没有数据，使用静态数据
      if (this.problemTypes.length === 0) {
        this.problemTypes = ['头发长', '腰带佩戴不规范', '穿冬袜'];
        this.problemCounts = [2, 4, 5];
      }

      // 初始化图表
      this.$nextTick(() => {
        this.initChart();
      });
    },

    initChart() {
      if (!this.$refs.barChart) {
        console.error('图表容器不存在');
        return;
      }

      if (this.barChart) {
        this.barChart.dispose();
      }

      try {
        this.barChart = echarts.init(this.$refs.barChart);
      } catch (error) {
        console.error('初始化图表失败:', error);
        return;
      }

      const option = {
        title: {
          text: '风纪问题统计',
          textStyle: {
            color: '#d3d6dd',
            fontSize: 18
          },
          left: 10,
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}人'
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.problemTypes,
          axisLine: {
            lineStyle: {
              color: '#d3d6dd'
            }
          },
          axisLabel: {
            interval: 0,
            rotate: 30,
            color: '#d3d6dd',
            fontSize: 16,
            margin: 8
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          nameTextStyle: {
            color: '#d3d6dd',
            fontSize: 16,
            padding: [0, 0, 0, 30]
          },
          axisLine: {
            lineStyle: {
              color: '#d3d6dd'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(211, 214, 221, 0.1)'
            }
          },
          axisLabel: {
            color: '#d3d6dd',
            fontSize: 16
          }
        },
        series: [
          {
            name: '问题人数',
            type: 'bar',
            data: this.problemCounts,
            barWidth: '35%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#4992ff' },
                { offset: 1, color: '#7cffb2' }
              ]),
              borderRadius: [5, 5, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              color: '#d3d6dd',
              fontSize: 16,
              formatter: '{c}人'
            }
          }
        ]
      };

      try {
        this.barChart.setOption(option);
      } catch (error) {
        console.error('设置图表选项失败:', error);
      }
    },

    resizeChart() {
      if (this.barChart) {
        this.barChart.resize();
      }
    },

    // 显示提示框
    showTooltip() {
      this.tooltipVisible = true;
    },

    // 隐藏提示框
    hideTooltip() {
      this.tooltipVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.discipline-status {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 10px;
  box-sizing: border-box;

  .module-title {
    font-size: 22px;
    color: #68d8fe;
    margin-bottom: 15px;
    font-weight: bold;
    padding-left: 10px;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 10px;

    .tooltip-container {
      position: relative;
      display: inline-block;
    }

    .info-btn {
      background: rgba(104, 216, 254, 0.2);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 4px;
      color: #68d8fe;
      cursor: pointer;
      padding: 4px 8px;
      font-size: 16px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(104, 216, 254, 0.3);
        border-color: rgba(104, 216, 254, 0.8);
        color: #ffffff;
        transform: scale(1.05);
      }

      i {
        font-size: 14px;
      }
    }

    .tooltip-box {
      background: rgba(19, 25, 47, 0.95);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 6px;
      padding: 24px 28px;
      color: #d3d6dd;
      font-size: 16px;
      line-height: 1.8;
      width: 450px;
      height: 350px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      word-wrap: break-word;
      white-space: normal;
      overflow-y: auto;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      text-align: left;

      &::before {
        content: '';
        position: absolute;
        bottom: -6px;
        left: -6px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-top: 6px solid rgba(104, 216, 254, 0.5);
      }

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: -5px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 5px solid rgba(19, 25, 47, 0.95);
      }
    }
  }

  .chart-container {
    flex: 1;
    width: 100%;
    height: calc(100% - 43px);
    min-height: 200px;
    margin-top: 20px;
  }

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #d3d6dd;
    font-size: 16px;
  }
}
</style>
